package com.wc.AlgoOJ.GR0102;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @Author congege
 * @Description 迷宫
 * http://43.138.190.70:8888/p/GR0102
 * @Date Created in 2023/12/22-10:24
 */
public class Main {
    static int maxN = 1000 + 10;
    static int[][] steps = new int[maxN][maxN];
//    static boolean[][][] vis = new boolean[maxN][maxN][4];
    static char[][] map = new char[maxN][];
    static int startX, startY;
    static int endX, endY;
    static int n, m;
    static int[] positionX = new int[]{-1, 0, 1, 0};
    static int[] positionY = new int[]{0, 1, 0, -1};
    static FastReader in = new FastReader();

    public static void main(String[] args) {
        init();
        n = in.nextInt();
        m = in.nextInt();
        for (int i = 0; i < n; i++) {
            String s = in.nextLine();
            int st = s.indexOf('S');
            int et = s.indexOf('E');
            if (st != -1) {
                startX = i;
                startY = st;
            }
            if (et != -1) {
                endX = i;
                endY = et;
            }
            map[i] = s.toCharArray();
        }
        steps[startX][startY] = 0;
        dfs(startX, startY, 0);
        System.out.println(steps[endX][endY] == maxN * maxN ? -1 : steps[endX][endY]);
    }

    private static void init() {
        for (int i = 0; i < maxN; i++) {
            Arrays.fill(steps[i], maxN * maxN);
        }
    }

    private static void dfs(int x, int y, int step) {
        if (x == endX && y == endY) {
            return;
        }
        for (int i = 0; i < 4; i++) {
            int nextX = x + positionX[i];
            int nextY = y + positionY[i];
            if (!isBorder(nextX, nextY) && (map[nextX][nextY] == '.' || map[nextX][nextY] == 'E') && (step + 1 < steps[nextX][nextY])) {
                steps[nextX][nextY] = step + 1;
                dfs(nextX, nextY, step + 1);
            }
        }
    }

    private static boolean isBorder(int x, int y) {
        return x < 0 || x == n || y < 0 || y == m;
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }
}
